// This is a JavaScript file
function BookmarkRegisterController(){ }
BookmarkRegisterController.prototype.params = {};

BookmarkRegisterController.prototype.isRegisterPage = true;

$(function(){
    
    var currentBmID;
    var currentBmData;
    
    var arrAllTagCode;      //get all keyword from keyword
    var arrRecommendTagCode; //get all recommentd key word
    var arrProductTagCode;  //get all taged keyword in product

    var isFirstLoad = true;
    var createdKeywordList = false;
    
    $(document).on('pageshow', '#pageBookmarkRegister', function(){
        PageChangeController.prototype.freeMemory();
 
        monaca.updateUIStyle("titlelable", "text", "ブックマーク");
        monaca.updateUIStyle("backheader", "visibility", "true");
        monaca.updateUIStyle("footer", "visibility", "false");
        
        Util.prototype.changeSnapperElement("bookmarkregister-content");
        
        handleChangePageKeyword(true);
        isFirstLoad = true;
        createdKeywordList = false;
        
        arrAllTagCode = [];
        arrRecommendTagCode = [];
        arrProductTagCode = [];
        var action = BookmarkRegisterController.prototype.params.action;
        currentBmID = BookmarkRegisterController.prototype.params.bm_id;

        currentBmData = {}; 
        $("#prod_pref-label").hide();
        $("#prod_pref").hide();
        $("#no_addressInfor").hide();
        
        if (action == 2) {
            $("#bt_bm_delete").hide();
            
            cloneBmObj(BookmarkRegisterController.prototype.params);
            $("#prod_name").val(currentBmData.item_name);
            $("#prod_memo").val(currentBmData.memo);
            // load genres
            displayGenresSelectBox(currentBmData.genre_code);
            // load keywords
            loadKeyword(currentBmData.genre_code);
        } else {
            if (action == 0) {
                $("#bt_bm_delete").show();
            } else {
                $("#bt_bm_delete").hide();
            }
            BookmarksService.prototype.loadBookmarkDataByID(currentBmID, true, function(results) {
                if (results.rows.length > 0) {
                    handleBmData(results.rows.item(0));
                } else {
                    BookmarksService.prototype.loadBookmarkDataByID(currentBmID, false, function(results) {
                        if (results.rows.length > 0) {
                            handleBmData(results.rows.item(0));
                        }
                    });
                }
            });
        }
    });
    
    function handleChangePageKeyword(isPageRegister) {
        BookmarkRegisterController.prototype.isRegisterPage = isPageRegister;
        if (isPageRegister) {
            $("#control_keyword").fadeOut("fast");
            $("#bookmark_form").fadeIn("fast");
            if ($('#prod_genre').prop('disabled')) {
                setTimeout(function() {
                    $('#prod_genre').selectmenu('enable');
                }, 1000); 
            }
        } else {
            $('#prod_genre').selectmenu('disable');
            $("#bookmark_form").fadeOut("fast"); 
            $("#control_keyword").fadeIn("fast");            
        }
    }

    function handleBmData (item) {
        $("#prod_name").val(item.item_name);
        $("#prod_memo").val(item.memo);
        if(typeof item.pref_name != "undefined" && typeof item.city_name != "undefined") {
            $("#prod_pref-label").show();
            $("#prod_pref").show();
            $("#prod_pref").val(item.pref_name + ' ' + item.city_name);
        } else {
            if(BookmarkRegisterController.prototype.params.scanAction == true && SettingService.prototype.isLocationAllow()) {
                $("#prod_pref-label").show();
                $("#no_addressInfor").show();
            }
        }
        
        cloneBmObj(item);
        // load genres
        displayGenresSelectBox(item.genre_code);
        // load keywords
        loadKeyword(item.genre_code);
    }
    
    var loadedGen = false, loadedKeys = false;
    
    function displayGenresSelectBox(genreId) {
        GenresService.prototype.getAllGenres(function(results){
            var options = "", select = $("#prod_genre");
            select.html('');
            for(var i = 0;i < results.rows.length; i ++){
        		var row = results.rows.item(i);
                var selected = (row.code == genreId) ? "selected" : "";
                options +="<option " + selected + " value =" + row.code +  ">" + row.name + "</option>";
    		}
            select.append(options);
            select.selectmenu('refresh');
            
            loadedGen = true;
            if (loadedKeys) {
                Util.prototype.refreshPageScroller();
                Util.prototype.hideSpinner();
            }
        });
    }
    
    function loadKeyword(genreId) {
        // load gerens and current item keyword
        KeywordsService.prototype.getKeywordByGenresId(genreId, function(results){
            var keys = '';
            var allGenKeys = [];
            for (var i = 0, j = results.rows.length; i < j; i ++) {
                var item = results.rows.item(i);            
                
                if (item.bookmark_id == currentBmID) {
                    keys += item.name + " ";
                    item.selected = true;
                    arrProductTagCode.push(item.id);
                } else {
                    item.selected = false;
                }
                var curArrIndex = allGenKeys.indexOf(item.id);
                if (curArrIndex < 0) {
                    arrRecommendTagCode.push(item);
                    allGenKeys.push(item.id);
                } else if (item.selected) {
                    arrRecommendTagCode.splice(curArrIndex, 1);
                    allGenKeys.splice(curArrIndex, 1);
                    
                    arrRecommendTagCode.push(item);
                    allGenKeys.push(item.id);
                }
            }
            
            $("#prod_keyword").val(keys);
            $("#prod_keyword2").val(keys);
            
            // load all keyword
            KeywordsService.prototype.getAllKeyword(function (results){
                for (var i = 0, j = results.rows.length; i < j; i ++) {
                    var item = results.rows.item(i);
                    var curArrIndex = arrProductTagCode.indexOf(item.id);
                    if (curArrIndex > -1) {
                        item.selected = true;
                    } else {
                        item.selected = false;
                    }
                    arrAllTagCode.push(item);
                }
                loadedKeys = true;
                if (loadedGen) {
                    Util.prototype.refreshPageScroller();
                    Util.prototype.hideSpinner();
                }
            });
        });
        
    }
    
    $(document).on("tap","#bt_bm_delete",function(){
        navigator.notification.confirm(Messages.prototype.BOOKMARK_DELETE, function(buttonIndex){
            if ( buttonIndex == 1 ){
                BookmarksService.prototype.deleteAdvanceBookmark([currentBmID], null, function() {
                    // alert("削除しました");
                    PageChangeController.prototype.changeToPage('pageHome');
                });
            }
        }, "削除確認", ["削除","キャンセル"]);
    });
    
    $(document).on('tap','#cancel_bookmark',function() {
        PageChangeController.prototype.goBack();
    });
    
    $(document).on('tap','#bt_save_bookmark',function(){
        Util.prototype.showSpinner();
        var newGenre = $("#prod_genre").val(),
            newMemo = $("#prod_memo").val().trim(),
            changeKw = false;
            
        if (createdKeywordList) {
            var newKeyword = splitKeywordString($("#prod_keyword").val());
            var newRelation = [], oldKeyword = [], newTmpKw = [];
            // oldKeyword  and Relation            
            $("#all_keyword a").each(function(index) {            
                var tagName =  $(this).attr('tag_name');
                var tagCode =  parseInt($(this).attr('tag_code'), 10);
                if ($(this).attr("class").indexOf("non-clicked")  == -1) {
                    if (arrProductTagCode.indexOf(tagCode) == -1) {
                        newRelation.push(tagCode);                    
                    }
                } else {
                    if (arrProductTagCode.indexOf(tagCode) > -1) {
                        oldKeyword.push(tagCode);
                    }
                }
                newTmpKw.push(tagName);
            });
        
            if (newKeyword.length > 0) {
                var refinedKw = [];
                $.each(newKeyword, function(i, keyword){
                    if($.inArray(keyword, refinedKw) === -1 && $.inArray(keyword, newTmpKw) === -1){
                        refinedKw.push(keyword);
                    }
                });
                newKeyword = null;
                newTmpKw = null;
                if (refinedKw.length > 0) {
                    currentBmData.newKeyword = refinedKw;
                    // console.log('new keyword: ' + refinedKw.toString());
                    if (!changeKw) {
                        changeKw = true;                        
                    }
                }
            }
            if (newRelation.length > 0) {
                currentBmData.newRelation = newRelation;
                // console.log('new relation: ' + newRelation.toString());
                if (!changeKw) {
                    changeKw = true;
                }
            }
            if (oldKeyword.length > 0) {
                currentBmData.oldKeyword = oldKeyword;
                // console.log('delete keyword: ' + oldKeyword.toString());
                if (!changeKw) {
                    changeKw = true;
                }
            }
        }
        var isBookmarked = $("#bt_bm_delete").is(':visible');
        if (isBookmarked && !changeKw && currentBmData.genre_code == newGenre && currentBmData.memo == newMemo) {
            // console.log('dont update');
            PageChangeController.prototype.changeToPage('pageHome');
            return;
        }

        currentBmData.id = currentBmID;
        // currentBmData.item_name = $("#prod_name").val();
        currentBmData.memo = newMemo;
        currentBmData.genre_code = newGenre;
        currentBmData.status = (typeof currentBmData.barcode_number != "undefined" && currentBmData.barcode_number != "") ? 2 : 1;

        if (typeof currentBmData.year == 'undefined' || parseInt(currentBmData.year, 10) < 0) {
            var today = Util.prototype.getTodayObj();
            currentBmData.registered_date = today.ymd;
            currentBmData.registered_month = today.m;
            currentBmData.registered_year = today.y;
        }        
        currentBmData.isBookmarked = isBookmarked;
        BookmarksService.prototype.saveBookmark(currentBmData, function(){
            PageChangeController.prototype.changeToPage('pageHome');
        });
    });
    
    $(document).on("tap", "#prod_keyword",function(){
        if (!createdKeywordList) {
            createdKeywordList = true;
        }
        handleChangePageKeyword(false);
                
        $('#tab-recommend').removeClass($.mobile.activeBtnClass);
        $('#tab-keyword').addClass($.mobile.activeBtnClass);        
        if (isFirstLoad) {
            createTagList(arrAllTagCode, $("#all_keyword"), true);
            createTagList(arrRecommendTagCode, $("#recommend_list"), false);
            isFirstLoad = false;
        } else {
            $("#all_keyword").show();
            $("#recommend_list").hide();
        }
    });
    
    function createTagList(tags, ui, isShow) {
        var html = '';            
        for (var i = 0; i < tags.length; i ++) {
            var item = tags[i];
            var clicked = item.selected ? 'clicked' : 'non-clicked';
            html += '<label class="tag-keyword-label"><a href="#" class="list-tag tag_code_' + item.id + ' ' + clicked + '" tag_code="' + item.id + '" tag_name="' + 
            item.name + '">' + item.name + " " + '</a></label>';
        }
        ui.html(html);
        if (typeof isShow != 'undefined') {
            if (isShow) {
                ui.show();
            } else {
                ui.hide();
            }
        }
    }
    
    $(document).on("tap",".tab_keyword ul li a",function(event){
        var this_id = $(this).attr("id");
        if (this_id == "tab-recommend") {
            $("#recommend_list").show();
            $("#all_keyword").hide();
        } else if (this_id == "tab-keyword") {
            $("#recommend_list").hide();
            $("#all_keyword").show();
        }
    });
    
    $(document).on("tap",".list-tag",function(){
        var isExit = $(this).attr("class").indexOf("non-clicked")  == -1;
        var tagCode = $(this).attr('tag_code');
        var tagName = $(this).attr('tag_name');
        var prod_keyword2 = $("#prod_keyword2");
        if (!isExit) {
            prod_keyword2.val(prod_keyword2.val()  + " " + tagName);
        } else {
            var key_array = splitKeywordString(prod_keyword2.val());
            for(var i=0; i< key_array.length; i++) { 
                if(tagName == key_array[i]) {
                    key_array.splice(i, 1);
                    break;
                }
            }
            var str = "";
            for(var i=0; i<key_array.length; i++) { 
                str += key_array[i]+ " ";
            }
            prod_keyword2.val(str);
        }
        $(".tag_code_" + tagCode).each(function() {
            $(this).toggleClass("clicked");
            $(this).toggleClass("non-clicked");
        });
    });
    
    $('#prod_keyword2').bind('input propertychange', function() {
        var string = splitKeywordString($("#prod_keyword2").val());	
        $(".list-tag").each(function(index) {
            var tagName =  $(this).attr('tag_name');
            if (string.indexOf(tagName) == -1) {
                if ($(this).attr("class").indexOf("non-clicked")  == -1) {
                    $(this).removeClass("clicked");
                    $(this).addClass("non-clicked");
                }               
            } else {
                if ($(this).attr("class").indexOf("non-clicked")  > -1) {
                    $(this).removeClass("non-clicked");
                    $(this).addClass("clicked");
                }  
            }
        });				
	});
    
    function splitKeywordString(string) {
        return string.trim().split(/\s+/);
    }

    $(document).on("tap","#bt_save_keyword",function(){
        var key_words = $("#prod_keyword2").val();
        $("#prod_keyword").val(key_words);        
        $("#prod_genre").removeAttr("autofocus");
        $("#prod_memo").attr("autofocus");
        handleChangePageKeyword(true);            
    });
    
    $(document).on('tap','#bt_clear_keyword',function() {
        $("#prod_keyword2").val($("#prod_keyword").val());
        createTagList(arrAllTagCode, $("#all_keyword"));
        createTagList(arrRecommendTagCode, $("#recommend_list"));
        handleChangePageKeyword(true);
    });
    
    function cloneBmObj (item) {
        for (var key in BookmarksService.prototype.DEFAULT_VALUES) {
            if (typeof item[key] != 'undefined') {
                currentBmData[key] = item[key];
            }
        }
    } 
    
    BookmarkRegisterController.prototype.freeMemory = function (isPageHome) {
        $("#prod_name").val("");
        $("#prod_memo").val("");
        $("#prod_pref").val("");
        $("#prod_keyword").val('');
        $("#prod_keyword2").val('');
        $("#recommend_list").html('');
        $("#all_keyword").html('');
        $("#prod_genre").html('');
        
        currentBmID = null;
        currentBmData = null;
        arrAllTagCode = null;
        arrRecommendTagCode = null;
        arrProductTagCode = null;
        
        if (isPageHome) {
            BookmarkRegisterController.prototype.params = null;
            BookmarkRegisterController.prototype.isRegisterPage = true;
        }
    };
    
    BookmarkRegisterController.prototype.backToRegisterPage = function() {
        if (!BookmarkRegisterController.prototype.isRegisterPage) {
            handleChangePageKeyword(true);
            return false;
        } else {
            return true;
        }
    };
});